package com.lastproject.ejb.dao;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.interceptor.Interceptors;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import annotations.PermissionAnnotation;

import com.lastproject.dto.SugestionDTO;
import com.lastproject.ejb.entities.Sugestion;
import com.lastproject.ejb.interceptors.PermissionInterceptor;
import com.lastproject.ejb.util.SugestionConversion;
import com.sun.org.apache.xpath.internal.axes.HasPositionalPredChecker;

/**
 * Session Bean implementation class SugestionDAO author : Dan Gandila
 */
@Stateless
public class SugestionDAO implements SugestionDAORemote {

	@PersistenceContext(unitName = "LastProjectEJB")
	private EntityManager em;
	@EJB
	SugestionConversion conv;

	public SugestionDAO() {
	}

	@Interceptors(PermissionInterceptor.class)
	@PermissionAnnotation(canAccessLibrary = 1)
	@Override
	public boolean create(boolean hasPermission, SugestionDTO entity) {
		if (hasPermission) {
			em.persist(conv.fromDTO(entity));
			return true;
		} else {
			return false;
		}
	}

	@Interceptors(PermissionInterceptor.class)
	@PermissionAnnotation(canAccessLibrary = 1)
	@Override
	public boolean edit(boolean hasPermission, SugestionDTO entity) {
		if (hasPermission) {
			em.merge(conv.fromDTO(entity));
			return true;

		} else {
			return false;
		}
	}

	@Interceptors(PermissionInterceptor.class)
	@PermissionAnnotation(canAccessLibrary = 1)
	@Override
	public boolean remove(boolean hasPermission, SugestionDTO entity) {
		if (hasPermission) {
			Sugestion s = em.find(Sugestion.class, entity.getId());
			em.remove(em.merge(s));
			return true;
		} else {
			return false;
		}

	}

	@Override
	public SugestionDTO findByID(Object id) {
		Sugestion s = em.find(Sugestion.class, id);
		SugestionDTO sugestion = conv.fromEntity(s);
		return sugestion;
	}

	@Override
	public List<SugestionDTO> findAll() {
		List<Sugestion> sugestions = em.createNamedQuery("Sugestion.findAll",
				Sugestion.class).getResultList();
		List<SugestionDTO> sugestionsDto = new ArrayList<SugestionDTO>();

		for (Sugestion s : sugestions) {
			SugestionDTO sDto = new SugestionDTO();
			sDto = conv.fromEntity(s);
			sugestionsDto.add(sDto);
		}
		return sugestionsDto;
	}

	@Override
	public List<SugestionDTO> findAllSortedByTitle() {
		List<Sugestion> sugestions = em
				.createQuery("SELECT s FROM Sugestion s ORDER BY s.subject",
						Sugestion.class).getResultList();
		List<SugestionDTO> sugestionsDto = new ArrayList<SugestionDTO>();

		for (Sugestion s : sugestions) {
			SugestionDTO sDto = new SugestionDTO();
			sDto = conv.fromEntity(s);
			sugestionsDto.add(sDto);
		}
		return sugestionsDto;
	}

}
